<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/10/29
 * Time: 10:39
 */

namespace app\adminapiv3\service;


class ServerDatabaseBak extends BaseService
{
    /**
     * @name 备份
     * @return bool
     * @author wx
     * @date 2019/10/29 11:23
     */
    public function backup()
    {
        //1. 备份
        $dbConfig = config('database.');
        $db_user = $dbConfig['username'];//数据库账号
        $db_pwd = $dbConfig['password'];//数据库密码
        $db_port = $dbConfig['hostport'];//端口
        $db_database = $dbConfig['database'];//数据库名

        $fileName = date("Y-m-d")."-".time();
        $bakDir = dirname($_SERVER['DOCUMENT_ROOT']).'/runtime/MysqlBak';//备份目录

        if (!file_exists($bakDir)) {
            mkdir($bakDir,0777,true);
        }
        $bakName = $bakDir.'/'.$fileName.'.sql';

        if(FALSE ===  stristr(php_uname('s'),"win"))
        {
            //linux备份
            $backupLinuxSql = "jzzdbback -u$db_user -p$db_pwd  -P$db_port $db_database >> $bakName";

            exec($backupLinuxSql);
        }
        else
        {
            //windows备份 ysqldump
            $mysqlExe = "D:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqldump.exe";
            //$backupWindowsSql = "#InstallPath#JZZDBBACK -u$db_user -p$db_pwd -P$db_port --default-character-set=utf8 $db_database >> $bakName";
            //$backupWindowsSql = "D:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqldump  JZZDBBACK -u$db_user -p$db_pwd -P$db_port --default-character-set=utf8 $db_database >> $bakName";
            $backupWindowsSql = "$mysqlExe -u$db_user -p$db_pwd -P$db_port --default-character-set=utf8 $db_database >> $bakName";

            exec($backupWindowsSql);
        }

        //2. 插入数据库
        $service = new \app\common\service\ServerDatabaseBak();
        $addData['path'] = $bakName;
        $addData['type'] = 1;
        $addData['ctime'] = time();

        $service->add($addData);

        return true;
    }

    /**
     * @name 备份列表
     * @param $params
     * @return array
     * @author wx
     * @date 2019/10/29 13:07
     */
    public function list($params)
    {
        $service = new \app\common\service\ServerDatabaseBak();
        $list = $service->list($params);

        foreach ($list['data'] as $k => $v){
            $list['data'][$k]['ctime'] = date("Y-m-d H:i:s",$v['ctime']);
        }

        return $list;
    }

    /**
     * @name 还原
     * @param $id
     * @return bool
     * @author wx
     * @date 2019/10/29 13:48
     */
    public function reset($id)
    {
        //1. 查找数据
        $service = new \app\common\service\ServerDatabaseBak();
        $info = $service->findData(['id' => $id]);

        if(!$info || !file_exists($info['path'])){
            $this->setError($this->CODE_FAIL, '未查询到该数据');
            return false;
        }

        //2. 还原
        $dbConfig = config('database.');

        $db_user = $dbConfig['username'];//数据库账号
        $db_pwd = $dbConfig['password'];//数据库密码
        $db_port = $dbConfig['hostport'];//端口
        $db_database = $dbConfig['database'];//数据库名

        if(FALSE ===  stristr(php_uname('s'),"win"))
        {
            //linux还原
            $resetSql = 'jzzdb -u'.$db_user.' -p'.$db_pwd .'   '. $db_database.'  -e  "source '.$info['path'].';" ';
        }
        else
        {
            //windows还原 mysql.exe
            $mysqlExe = "D:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysql.exe";
            $resetSql = $mysqlExe.' -u' .$db_user. " -p".$db_pwd." ".$db_database." < ".$info['path'];
        }

        exec($resetSql);

        return true;
    }


    /**
     * @name 清空备份数据
     * @return bool
     * @author wx
     * @date 2019/10/29 13:59
     */
    public function clear()
    {
        //1. 清空数据库
        $service = new \app\common\service\ServerDatabaseBak();
        $condition[] = array('id', '>=', 1);
        $service->del($condition);

        //2. 删除备份文件
        $path = '../runtime/MysqlBak/';
        if(is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是文件直接删除
                    unlink($path . $val);
                }
            }
        }

        return true;
    }


    /**
     * @name 数据库地址配置
     * @param $ip
     * @param $port
     * @return bool
     * @author wx
     * @date 2019/11/29 13:23
     */
    public function databaseConf($ip, $port)
    {
        $path = '../runtime/config/database.conf';
        $data['ip'] = $ip;
        $data['port'] = $port;

        file_put_contents($path,json_encode($data));

        return true;
    }

    /**
     * @name 获取数据库地址配置
     * @return mixed
     * @author wx
     * @date 2019/11/29 13:36
     */
    public function databaseGet()
    {
        $path = '../runtime/config/database.conf';

        if (file_exists($path)) {

            $content = file_get_contents($path);
            $databaseConf = json_decode($content, true);

        }else{

            $databaseConf['ip'] = '';
            $databaseConf['port'] = '';
        }

        return $databaseConf;
    }
}